﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mono.Cecil;
using System.IO;

namespace devtm.Aop
{

    public class CustomAssemblyResolver : DefaultAssemblyResolver
    {


        public override AssemblyDefinition Resolve(AssemblyNameReference name)
        {
            return base.Resolve(name);
        }

        public override AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters)
        {

           
            if (!parameters.ReadSymbols)
            {

                string fullname = SearchDirectory(name, this.GetSearchDirectories());
                string pdbFilename = GetPdbFilename(fullname);

                if (File.Exists(pdbFilename))
                {
                    parameters.SymbolReaderProvider = new Mono.Cecil.Pdb.PdbReaderProvider();
                    parameters.ReadSymbols = true;
                }
            }


            AssemblyDefinition ass = base.Resolve(name, parameters);

            //AssemblyDefinition ass = AssemblyDefinition.ReadAssembly(name.Name, parameters);
            base.RegisterAssembly(ass);
            
            return ass;

        }


        string SearchDirectory(AssemblyNameReference name, IEnumerable<string> directories)
        {
            var extensions = new[] { ".dll", ".exe" };

            foreach (var extension in extensions)
            {
                foreach (var directory in directories)
                {
                    string file = Path.Combine(directory, name.Name + extension);
                    if (File.Exists(file))
                        return file;
                }
            }

            return null;
        }


        public override AssemblyDefinition Resolve(string fullName)
        {
            return base.Resolve(fullName);
        }

        //public override AssemblyDefinition Resolve(string fullName, ReaderParameters parameters)
        //{

        ////  if (!parameters.ReadSymbols)
        //    {
        //        string pdbFilename = GetPdbFilename(fullName);
        //        if (File.Exists(pdbFilename))
        //
        
        //            parameters.SymbolReaderProvider = new Mono.Cecil.Pdb.PdbReaderProvider();
        //r();
        //rameters.ReadSymbols = true;
        //        }
        //       }
       //    return base.Resolve(fullName, parameters);
        //}

        private static string GetPdbFilename(string filename)
        {
            return Path.ChangeExtension(filename, ".pdb");
        }
    }
}
